#!/usr/bin/env python3
"""
Usage Example for GSI/EnKF Automated Code Commentary System

This script demonstrates how to use the automated code commentary system
to process GSI/EnKF Fortran source code.

Author: GSI Development Team
Date: 2025-01-XX
"""

import os
import sys
from pathlib import Path
import logging

from fortran_commentator import CodeCommentarySystem

def main():
    """Example usage of the code commentary system"""
    
    # Configuration
    gsi_base_path = "/home/docker/comgsi/tutorial/comGSIv3.7_EnKFv1.3/src"
    config_dir = "/home/docker/comgsi/tutorial/comGSIv3.7_EnKFv1.3/src/comGSI-doc/config"
    ollama_url = "http://60.245.128.27:11434" 
    model_name = "hopephoto/qwen3-30b-a3b-instruct_q8:latest"
    worker_count = 4
    
    print("GSI/EnKF Automated Code Commentary System")
    print("=" * 50)
    print(f"GSI Path: {gsi_base_path}")
    print(f"Config Dir: {config_dir}")
    print(f"Ollama URL: {ollama_url}")
    print(f"Model: {model_name}")
    print(f"Workers: {worker_count}")
    print()
    
    # Check paths exist
    if not Path(gsi_base_path).exists():
        print(f"❌ GSI path does not exist: {gsi_base_path}")
        return 1
        
    if not Path(config_dir).exists():
        print(f"❌ Config directory does not exist: {config_dir}")
        return 1
    
    try:
        # Initialize the commentary system
        print("🔧 Initializing commentary system...")
        commentary_system = CodeCommentarySystem(
            gsi_base_path=gsi_base_path,
            config_dir=config_dir,
            ollama_url=ollama_url,
            model_name=model_name
        )
        
        # Test connection first
        print("🌐 Testing Ollama connection...")
        if not commentary_system.ollama_manager.test_connection():
            print("❌ Failed to connect to Ollama model")
            print("   Please ensure:")
            print("   1. Ollama server is running")
            print("   2. Model is available: ollama pull hopephoto/qwen3-30b-a3b-instruct_q8:latest")
            print("   3. Server URL is correct")
            return 1
        
        print("✅ Ollama connection successful")
        
        # Discover files
        print("📂 Discovering Fortran files...")
        all_files = commentary_system.discover_fortran_files()
        print(f"   Found {len(all_files)} total Fortran files")
        
        # Filter files
        filtered_files = commentary_system.file_processor.filter_files_by_size(all_files)
        print(f"   Filtered to {len(filtered_files)} files (≤1500 lines)")
        
        if len(filtered_files) == 0:
            print("⚠️  No files to process after filtering")
            return 0
        
        # Show sample of files to be processed
        print("\n📋 Sample files to be processed:")
        for i, file_path in enumerate(filtered_files[:5]):
            classification = commentary_system.classifier.classify_file(file_path)
            line_count = commentary_system.file_processor.count_lines(file_path)
            relative_path = Path(file_path).relative_to(gsi_base_path)
            print(f"   {i+1}. {relative_path} ({classification}, {line_count} lines)")
        
        if len(filtered_files) > 5:
            print(f"   ... and {len(filtered_files) - 5} more files")
        
        # Ask for confirmation
        print("\n⚠️  This will modify Fortran source files (backups will be created)")
        response = input("Continue with processing? [y/N]: ").strip().lower()
        
        if response not in ['y', 'yes']:
            print("❌ Processing cancelled by user")
            return 0
        
        # Process codebase
        print(f"\n🚀 Starting processing with {worker_count} workers...")
        results = commentary_system.process_codebase(worker_count=worker_count)
        
        # Display results
        print("\n📊 Processing Results:")
        print("=" * 30)
        print(f"Total files: {results.total_files}")
        print(f"Successful: {len(results.successful_files)}")
        print(f"Failed: {len(results.failed_files)}")
        print(f"Processing time: {results.processing_time:.2f} seconds")
        print(f"Average time per file: {results.processing_time/max(1,results.total_files):.2f} seconds")
        
        if results.failed_files:
            print("\n❌ Failed Files:")
            for file_path, error in results.failed_files:
                relative_path = Path(file_path).relative_to(gsi_base_path)
                print(f"   {relative_path}: {error}")
        
        if len(results.successful_files) > 0:
            print(f"\n✅ Successfully processed {len(results.successful_files)} files")
            print("   Backup files created with .backup extension")
            print("   Log file: code_commentary.log")
            print("   Results file: config/processing_results.json")
        
        print("\n🎉 Processing complete!")
        return 0
        
    except KeyboardInterrupt:
        print("\n❌ Processing interrupted by user")
        return 1
    except Exception as e:
        print(f"\n💥 Error during processing: {e}")
        logging.exception("Unexpected error in commentary system")
        return 1


if __name__ == "__main__":
    exit_code = main()
    sys.exit(exit_code)